import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { Post, Prisma } from '@prisma/client';
import { PostDto } from './dto';

@Injectable()
export class PostService {
  constructor(private prisma: PrismaService) { }

  async post(post: Prisma.PostWhereUniqueInput): Promise<Post | null> {
    // 更新的原子操作可用于数字字段类型（Float 和 Int）。此功能允许您根据其 当前值（例如 减法 或 除法）更新字段，而不会冒竞争条件的风险。
    type UpdateOperationsInput = {
      increment?: number
    }
    let views: UpdateOperationsInput = { increment: 1 }
    try {
      await this.prisma.post.update({ where: post, data: { views } })
    } catch (error) {
      
    }
    return this.prisma.post.findUnique({ where: post })
  }

  async posts(skip: number, take: number): Promise<PostDto> {
    let count = await this.prisma.post.count()
    let data = await this.prisma.post.findMany({ take, skip })
    return { count, data }
  }

  async createPost(data: Prisma.PostCreateInput): Promise<Post> {
    return this.prisma.post.create({ data })
  }

  async updatePost(params: { where: Prisma.PostWhereUniqueInput, data: Prisma.PostUpdateInput }): Promise<Post> {
    const { where, data } = params
    return this.prisma.post.update({ where, data })
  }

  async deletePost(where: Prisma.PostWhereUniqueInput): Promise<Post> {
    return this.prisma.post.delete({ where })
  }
}
